$(document).ready(function() {
	loadList();
});

$('#btnSearch').click(function() {
	loadList();
});

// Load station details
$('#lstName').change(function() {
	var value = $('#lstName option:selected').val();
	$.post("<?=site_url('station/getStation')?>", {
		"id" : value
	}, function(data) {
		$('#id').val(value);
		$('#name').val(data.name);
		$('#address').val(data.address);
		$('#city').val(data.city);
	}, "json");
});

$('#btnEdit').click(function() {
	if ($('#name').val() == '')
		return;

	if ($(this).val() == 'Edit') {
		$(this).val('Save');
		$('#btnDelete').val('Cancel');
		inputEnabled(true);
	} else {
		update();
	}
});

function update() {
	$.post("<?=site_url('station/editStation')?>",
			$('#frmDetails').serialize(), function(data) {
				var res = data.response;
				var msg = data.message;

				if (res == 1) {
					alert('Success: ' + msg);

					$('#btnEdit').val('Edit');
					$('#btnDelete').val('Delete');
					inputEnabled(false);
					loadList();
				} else {
					alert('Failed: ' + msg);
				}
			}, "json");
}

function inputEnabled(enabled) {
	if (enabled) {
		$('#name').removeAttr('disabled');
		$('#address').removeAttr('disabled');
		$('#city').removeAttr('disabled');
	} else {
		$('#name').attr('disabled', 'disabled');
		$('#address').attr('disabled', 'disabled');
		$('#city').attr('disabled', 'disabled');
	}
}

function loadList() {
	$('#lstName').html('');
	var q = $('#txtSearch').val();
	$.post("<?=site_url('station/getAllStations')?>", {
		"q" : q
	}, function(data) {
		$.each(data, function(key, val) {
			$('#lstName').append(
					"<option value='" + key + "'>" + val + "</option>\n");
		});
	}, "json");
}